# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(optparse)
library(stringr)
library(magrittr)
library(tidyverse)
library(tools)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))

configData

tbf <- tibble()

diffFileNames <- configGet(configData, "diffFiles") %>%
  str_split(":") %>%
  unlist()

labels <- read_tsv("Class_Color.txt") %>%
  .$ClassNote

for (i in 1:length(diffFileNames)) {
  fileName <- diffFileNames[i]
  label <- labels[i]
  names <- fileName %>%
    str_split("/") %>%
    unlist()
  newFileName <- fileName %>%
    str_split("/") %>%
    unlist() %>%
    tail(., 2) %>%
    str_c(collapse = "_") %>%
    str_replace(., ".csv$", ".txt")
  data <- read_tsv(str_c(newFileName)) %>%
    select("Metabolite") %>%
    rename_at(vars(c("Metabolite")), function(x) {
      c(label)
    })

  if (nrow(data) > 0) {
    data <- data %>%
      mutate(id = 1:n())
  }else {
    data <- data %>%
      add_column(id = NA)
  }
  if (ncol(tbf) == 0) {
    tbf <- data
  }else {
    tbf <- tbf %>%
      full_join(data, by = "id")
  }
}

columnNames <- labels
outData <- tbf
size <- length(columnNames)

if (length(columnNames) > 1 & length(columnNames) <= 4) {
  for (i in size:2) {
    cn <- combn(columnNames, i)
    for (i in 1:ncol(cn)) {
      row <- cn[, i]
      columnName <- str_c(row, collapse = " & ")
      outData <- outData %>%
        mutate(!!columnName := {
          values <- row %>%
            map(function(t) {
              get(t)
            })
          x <- Reduce(intersect, values)
          x[1:n()]
        })
    }
  }
}else if (length(columnNames) > 4) {
  for (i in size:size) {
    cn <- combn(columnNames, i)
    for (i in 1:ncol(cn)) {
      row <- cn[, i]
      columnName <- str_c(row, collapse = " & ")
      outData <- outData %>%
        mutate(!!columnName := {
          values <- row %>%
            map(function(t) {
              get(t)
            })
          x <- Reduce(intersect, values)
          x[1:n()]
        })
    }
  }
}

if (length(columnNames) <= 4) {
  for (name in columnNames) {
    newName <- str_c(name, " only")
    outData <- outData %>%
      mutate(!!newName := {
        otherNames <- columnNames %>%
          discard(~.x %in% c(name))
        values <- c(name, otherNames) %>%
          map(function(t) {
            get(t)
          })
        x <- Reduce(setdiff, values)
        x[1:n()]
      })
  }
}

outData <- outData %>%
  mutate_all(function(x) {
    replace_na(x, "")
  })

if (length(columnNames) > 4) {
  outData <- outData %>%
    select((size + 2), columnNames)
}else {
  outData <- outData %>%
    select(-c(1:(size + 1)))
}

outData
write_csv(outData, "Venn_Data.csv")




















